/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    TreeNode *reverseOddLevels(TreeNode *root)
    {
        vector<TreeNode *> layer1, layer2;
        bool isOddLayer = false;
        layer1.push_back(root);
        while (layer1[0] != nullptr)
        {
            if (isOddLayer)
            {
                int n = layer1.size() / 2;
                for (int i = 0; i < n; ++i)
                {
                    swap(layer1[i]->val, layer1[2 * n - i - 1]->val);
                }
            }
            for (TreeNode *t : layer1)
            {
                layer2.push_back(t->left);
                layer2.push_back(t->right);
            }
            layer1.clear();
            layer1.swap(layer2);
            isOddLayer = !isOddLayer;
        }
        return root;
    }
};